<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    form
    :width="640"
    :model-value="modelValue"
    :title="isUpdate ? '修改用户' : '新建用户'"
    @update:modelValue="updateModelValue"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
      <el-row :gutter="16">
        <el-col :sm="24" :xs="24">
          <el-form-item label="用户账号" prop="username">
            <el-input
              clearable
              :maxlength="20"
              v-model="form.username"
              placeholder="请输入用户账号"
              :disabled="isUpdate"
            />
          </el-form-item>
          <el-form-item label="姓名" prop="realname">
            <el-input
              clearable
              :maxlength="20"
              v-model="form.realname"
              placeholder="请输入姓名"
            />
          </el-form-item>
          <el-form-item label="部门" prop="roles">
            <el-select
              clearable
              v-model="form.roles"
              placeholder="请选择部门"
              class="ele-fluid"
            >
              <el-option
                v-for="item in rolesList"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              >
                {{ item.title }}
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="管辖区域" prop="area_id">
            <area-select v-model="form.area_id" />
          </el-form-item>

          <el-form-item v-if="!isUpdate" label="登录密码" prop="password">
            <el-input
              show-password
              type="password"
              :maxlength="20"
              v-model="form.password"
              placeholder="请输入登录密码"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="updateModelValue(false)">取消</el-button>
      <el-button type="primary" :loading="loading" @click="save">
        保存
      </el-button>
    </template>
  </ele-modal>
</template>

<script setup>
  import { ref, reactive, watch } from 'vue';
  import { EleMessage } from 'ele-admin-plus/es';
  import { useFormData } from '@/utils/use-form-data';
  import AreaSelect from './area-select.vue';
  import { addUser, updateUser } from '@/api/system/user';
  import { listRoles } from '@/api/system/role';

  const emit = defineEmits(['done', 'update:modelValue']);

  const props = defineProps({
    /** 弹窗是否打开 */
    modelValue: Boolean,
    /** 修改回显的数据 */
    data: Object
  });

  /** 是否是修改 */
  const isUpdate = ref(false);

  /** 提交状态 */
  const loading = ref(false);

  /** 表单实例 */
  const formRef = ref(null);

  /** 部门列表 */
  const rolesList = ref([]);

  /** 表单数据 */
  const [form, resetFields, assignFields] = useFormData({
    id: 0,
    username: '',
    realname: '',
    area_id: [],
    roles: void 0,
    password: ''
  });

  /** 表单验证规则 */
  const rules = reactive({
    username: [
      {
        required: true,
        message: '请输入用户账号',
        type: 'string',
        trigger: 'blur'
      },
      {
        min: 2,
        message: '账号长度最少为2位',
        type: 'string',
        trigger: 'blur'
      }
      // {
      //   type: 'string',
      //   trigger: 'blur',
      //   validator: (_rule, value, callback) => {
      //     checkExistence({ username: value, id: props.data?.id })
      //       .then(() => {
      //         callback(new Error('账号已经存在'));
      //       })
      //       .catch(() => {
      //         callback();
      //       });
      //   }
      // }
    ],
    realname: [
      {
        required: true,
        message: '请输入姓名',
        type: 'string',
        trigger: 'blur'
      }
    ],

    area_id: [
      {
        required: true,
        message: '请选择站点',
        type: 'array',
        trigger: 'blur'
      }
    ],

    roles: [
      {
        required: true,
        message: '请选择部门',
        type: 'int',
        trigger: 'blur'
      }
    ],

    password: [
      {
        required: true,
        message: '请输入登录密码',
        type: 'string',
        trigger: 'blur'
      },
      {
        type: 'string',
        trigger: 'blur',
        validator: (_rule, value, callback) => {
          if (isUpdate.value || /^[\S]{5,18}$/.test(value)) {
            return callback();
          }
          callback(new Error('密码必须为5-18位非空白字符'));
        }
      }
    ]
  });

  /** 保存编辑 */
  const save = () => {
    console.log(form);
    formRef.value?.validate?.((valid) => {
      if (!valid) {
        return;
      }
      loading.value = true;
      const saveOrUpdate = isUpdate.value ? updateUser : addUser;
      saveOrUpdate(form)
        .then((msg) => {
          loading.value = false;
          EleMessage.success(msg);
          updateModelValue(false);
          emit('done');
        })
        .catch((e) => {
          loading.value = false;
          EleMessage.error(e.message);
        });
    });
  };

  /** 更新modelValue */
  const updateModelValue = (value) => {
    emit('update:modelValue', value);
  };

  /** 获取角色数据 */
  listRoles({})
    .then((res) => {
      rolesList.value = res.list;
    })
    .catch((e) => {
      EleMessage.error(e.message);
    });

  watch(
    () => props.modelValue,
    (modelValue) => {
      if (modelValue) {
        if (props.data) {
          assignFields({
            ...props.data,
            password: ''
          });
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
        formRef.value?.clearValidate?.();
      }
    }
  );
</script>
